/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tcr.main;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.tcr.entities.Enseigne;
import com.tcr.entities.Restaurant;
import com.tcr.main.R;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.lang.Class;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectReader;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

/**
 *
 * @author Alexia De Medeiros
 */
public class RechercheEnseigne extends Activity {

    private Button chercherB;
    private String Enseigne;
    private String Ville;
    private RadioGroup RadioType;
    private String Type;
    private ListView listens;
    private ArrayList<Enseigne> enseignes = new ArrayList<Enseigne>();
    private final String URLTCR = "http://10.0.2.2:8080/TheCityRater-war/services/enseignes/";
    private ObjectMapper objectMapper = null;
    Bundle objetbunble = new Bundle();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rechercheenseigne);

        chercherB = (Button) findViewById(R.recherche.recherche);

        chercherB.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                recherche();
            }
        });
    }

    public void recherche() {
        Enseigne = ((TextView) findViewById(R.recherche.Enseigne)).getText().toString();
        Ville = ((TextView) findViewById(R.recherche.Ville)).getText().toString();
        RadioType = (RadioGroup) findViewById(R.recherche.Type);
        Type = ((TextView) (RadioType.findViewById(RadioType.getCheckedRadioButtonId()))).getText().toString();
        listens = (ListView) findViewById(R.recherche.listEns);
        connect("rechercheenseigne", Enseigne, Ville, Type);

        if (enseignes != null) {
            for (int i = 0; i < enseignes.size(); i++) {
                objetbunble.putString(enseignes.get(i).getNom(), enseignes.get(i).getDescription());
            }
        }
        //Création de la ArrayList qui nous permettra de remplire la listView
        ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();

        //On déclare la HashMap qui contiendra les informations pour un item
        HashMap<String, String> map;
        Intent thisIntent = getIntent();

        Set<String> keys = objetbunble.keySet();
        Iterator<String> iterate = keys.iterator();
        while (iterate.hasNext()) {
            map = new HashMap<String, String>();
            String key = iterate.next();
            map.put("titre", key);
            map.put("description", objetbunble.get(key).toString());
            listItem.add(map);
        }

        //Création d'un SimpleAdapter qui se chargera de mettre les items présent dans notre list (listItem) dans la vue affichageitem
        SimpleAdapter mSchedule = new SimpleAdapter(this.getBaseContext(), listItem, R.layout.affichageitem,
                new String[]{"titre", "description"}, new int[]{R.id.titre, R.id.description});

        //On attribut à notre listView l'adapter que l'on vient de créer
        listens.setAdapter(mSchedule);

        listens.setVisibility(TextView.VISIBLE);
    }

    public void connect(String url, String Enseigne, String Ville, String Type) {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            String conc = URLTCR + url;
            HttpPost httpPost = new HttpPost(URLTCR + url);
            // On créer un objet JSON qui sera transmis au serveur
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("NOM", Enseigne);
            jsonObject.put("VILLE", Ville);
            jsonObject.put("TYPE", Type);
            jsonObject.put("START", 0);
            jsonObject.put("NB", 5);


            // On transforme le JSON afin de pouvoir transmettre les informations
            StringEntity stringEntity = new StringEntity(jsonObject.toString());
            stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setEntity(stringEntity);
            HttpResponse response;

            response = httpclient.execute(httpPost);

            Log.i("Praeda", response.getStatusLine().toString());

            HttpEntity entity = response.getEntity();
            InputStream input = entity.getContent();
            if (input != null) {
                objectMapper = new ObjectMapper();
                /*Object object = input.readObject();
                while (object != null) {
                enseignes.add((Enseigne) object);
                object = input.readObject();
                
                }
                input.close();
                enseignes = new ArrayList<Restaurant>();
                Class<ArrayList<Restaurant>> c = (Class<ArrayList<Restaurant>>) enseignes.getClass();
                //if(Type.equals("Restaurant"))
                objectMapper.enableDefaultTyping();
                enseignes = objectMapper.readValue(input, c);*/
                enseignes = objectMapper.readValue(input, new TypeReference<ArrayList<Enseigne>>() {
                });
            }
        } catch (Exception ex) {
            System.out.println("test" + ex);
        }
    }
}
